package com.bootdo.system.filter;

import com.bootdo.system.domain.FrontuserDO;
import com.bootdo.system.service.FrontuserService;
import com.bootdo.system.utils.MyConstant;
import com.bootdo.system.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private FrontuserService frontuserService;


    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否登陆逻辑
        //获取当前站点的所有Cookie
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            log.info("进入拦截器cookies==null");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();

            writer.write(R.error().put("login","nocookie").toString());
            return false;
        }
        for (int i = 0; i < cookies.length; i++) {//对cookies中的数据进行遍历，找到用户名、密码的数据
            if (cookies[i] == null) {
                continue;
            }
            if (MyConstant.WEBCOOKIE.equals(cookies[i].getName())) {
                final String pass = cookies[i].getValue();
                log.info("用户存在coolie pass=" + pass);
                FrontuserDO  frontuserDO = frontuserService.getUserByPassword(pass);
                if (frontuserDO != null) {
                    request.getSession().setAttribute("user", frontuserDO);
                    return true;
                }
            }
        }


        //检测session
        final Object user = request.getSession().getAttribute("user");
        if (user == null) {
            log.info("进入拦截器user == null");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(R.error().put("login","nocookie").toString());
            return false;
        }

        return true;
    }





}
